package com.zh.common.base

import android.app.Activity
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import androidx.multidex.MultiDexApplication
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.mmkv.MMKV
import com.zh.common.BuildConfig
import com.zh.common.R
import com.zh.common.utils.toast.BkjToast
import com.zh.common.utils.toast.ZToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.unit.Subunits
import me.jessyan.autosize.utils.ScreenUtils
import kotlin.system.measureTimeMillis

open class BaseApplication : MultiDexApplication() {

    //让外部获取到BaseApplication
    companion object {
        @JvmStatic
        lateinit var instance: BaseApplication
            private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        val time = measureTimeMillis {
            //初始化微信存储
            MMKV.initialize(this@BaseApplication)
            //组件化实例化
            initARouter()
            //初始化所有数据
            onCreateMethod()
            GlobalScope.launch(Dispatchers.IO) {//异步初始化
                //今日头条适配
                initAutoSize()
                //Toast实例化
                ZToastUtils.init(BkjToast())
            }
        }
        LogUtils.e("Application初始化用时---$time")
    }

    /**
     * 初始化操作
     */
    open fun onCreateMethod() {}

    private fun initARouter() {
        if (BuildConfig.DEBUG) { // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog() // 打印日志
            ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this) // 尽可能早，推荐在Application中初始化
    }

    /**
     * 初始化今日头条适配
     */
    private fun initAutoSize() {
        //获取meta-data配置的数据
        val appInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            this.packageManager.getApplicationInfo(
                packageName, PackageManager.ApplicationInfoFlags.of(0)
            )
        } else {
            this.packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        }
        val widthSize = appInfo.metaData?.getInt("design_width_in_dp", 375) ?: 375
        val heightSize = appInfo.metaData?.getInt("design_height_in_dp", 667) ?: 667
        //初始化今日头条配置
        val config = AutoSizeConfig.getInstance()
        config.isBaseOnWidth = true//是否全局按照宽度进行等比例适配
        config.isExcludeFontScale = true//是否屏蔽系统字体大小对 AndroidAutoSize 的影响
        config.unitsManager.supportSubunits = Subunits.MM//让 AndroidAutoSize 以什么单位为副单位
        config.onAdaptListener = object : onAdaptListener {
            //设置屏幕适配监听器
            override fun onAdaptBefore(target: Any?, activity: Activity?) {
                activity?.let {
                    config.screenWidth = ScreenUtils.getScreenSize(it)[0]
                    config.screenHeight = ScreenUtils.getScreenSize(it)[1]
                    //横竖屏切换的监听
                    if (it.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                        config.isBaseOnWidth = true
                        config.designWidthInDp = widthSize
                        config.designHeightInDp = heightSize
                    } else {
                        config.isBaseOnWidth = false
                        config.designHeightInDp = widthSize
                        config.designWidthInDp = heightSize
                    }
                }
            }

            override fun onAdaptAfter(target: Any?, activity: Activity?) {

            }
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        ARouter.getInstance().destroy()
    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            MaterialHeader(context).setColorSchemeResources(
                R.color.colorPrimary, R.color.colorAccent, R.color.colorPrimaryDark
            )
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }
}